import { useAsyncEffect } from '@gnlab/utils/env-react'
import { Spin, message, Modal, Table } from 'antd'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import services from '@/services'
import type {
  SendMomentConfig,
  SendMomentTask,
  SendMomentConfigQywx,
} from '@/services/features/send-moment'
import { SendMomentTaskStatus, SendMomentConfigStatus } from '@/services/features/send-moment'
import './index.module.less'

export default function ConfigTasksModal(props: {
  config?: SendMomentConfig
  onClose: () => void
}) {
  const { config, onClose } = props

  return <Modal
    styleName="modal"
    title={config ? `${config.name} 详情` : ''}
    footer={null}
    width="800px"
    open={!!config}
    onCancel={onClose}
    maskClosable
    destroyOnClose
  >
    {config ? <Content config={config} /> : null}
  </Modal>
}

function Content(props: { config: SendMomentConfig }) {
  const { config } = props

  const [qywxs, setQywxs] = useState<Map<string, SendMomentConfigQywx>>(new Map()) // 此配置下的企业微信信息
  const [tasks, setTasks] = useState<SendMomentTask[] | null>(null)
  const loadTasks = useCallback(async () => {
    const res = await services.features.sendMoment.loadTasks(config.id)
    if (!res.success) return void message.warning(`任务详情获取失败：${res.error}`)
    setTasks(res.data)
  }, [config])
  useEffect(() => {
    void loadTasks()
  }, [loadTasks])

  useAsyncEffect(async () => {
    const res = await services.features.sendMoment.getQywxListForConfig(config.id)
    if (res.success) setQywxs(new Map(res.data.map(qywx => [qywx.wxid, qywx])))
    else void message.warning('获取企业微信列表失败')
  }, [config])

  const renderQywx = useCallback(
    (task: SendMomentTask) => {
      const qywx = qywxs.get(task.wxid)
      if (!qywx) return null
      return <div styleName="qywx-info">
        <img src={qywx.avatar || defaultAvatar} />
        <div styleName="info-main">
          <div styleName="name">{qywx.friendlyName}</div>
          <div styleName="corp">{qywx.corpname}</div>
        </div>
      </div>
    },
    [qywxs],
  )

  const renderContacts = useCallback((task: SendMomentTask) => {
    if (!task.contacts) return <span styleName="contacts-all">全部联系人</span>
    return task.contacts.length
  }, [])

  const renderStatus = useCallback(
    (task: SendMomentTask) => {
      const map = new Map([
        [
          SendMomentTaskStatus.Idle,
          config.status === SendMomentConfigStatus.Cancelled ? '已取消' : '待发送',
        ],
        [SendMomentTaskStatus.Sended, '已发送'],
        [SendMomentTaskStatus.Failed, '发送失败' + (task.message ? '，' + task.message : '')],
      ])
      return map.get(task.status)!
    },
    [config],
  )

  return <div>
    {!tasks ? (
      <div styleName="loading">
        <Spin tip="加载中..." size="large" />
      </div>
    ) : null}

    {tasks ? (
      <div styleName="qywxs">
        <Table<SendMomentTask>
          rowKey="wxid"
          dataSource={tasks}
          scroll={{ y: 500 }}
          pagination={false}
        >
          <Table.Column<SendMomentTask> title="企微账号" width={300} render={renderQywx} />
          <Table.Column<SendMomentTask>
            title="预计发送人数"
            align="center"
            width={180}
            render={renderContacts}
          />
          <Table.Column<SendMomentTask> title="状态" render={renderStatus} />
        </Table>
      </div>
    ) : null}
  </div>
}
